//
//  ViewController.swift
//  ML
//
//  Created by MoneyLee on 2020/8/21.
//  Copyright © 2020 MoneyLee. All rights reserved.
//

import UIKit
//机器学习必须引用的
import CoreML
//视界 图像类的工具
import Vision

class ViewController: UIViewController {

    @IBOutlet weak var showImgV: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }

    @IBAction func camreClick(_ sender: UIBarButtonItem) {
        
        let picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType = .camera
        present(picker, animated: true, completion: nil)
        
    }
    
}

extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
        if let img = info[.originalImage] as? UIImage {
            showImgV.image = img
            navigationItem.title = "识别中..."
            //转化为CIImage
            guard let ciImg = CIImage(image: img) else {
                fatalError("不能把图像转化为CIImage")
            }
            //加载训练好的模型
            guard let model = try? VNCoreMLModel(for: MobileNetV2FP16().model) else {
                fatalError("加载ML Model失败")
            }
            
            //创建识别请求
            let request = VNCoreMLRequest(model: model) { (req, error) in
                //请求的回调 res 识别的结果
                guard let res = req.results else {
//                    fatalError("图像识别失败")
                    self.navigationItem.title = "图片识别失败"
                    return
                }
                
                let classifcations = res as! [VNClassificationObservation]
                if classifcations.isEmpty {
                    print("没有识别成功")
                    self.navigationItem.title = "没有识别成功"
                } else {
                    //取识别概率最大的结果
                    print(classifcations.first!.identifier)
                    self.navigationItem.title = classifcations.first!.identifier
                }
                
            }
            //苹果的model图像是正方型, 我们将获取的图像转换为正方型 有助于识别, 默认是原图
            request.imageCropAndScaleOption = .centerCrop
            
            //执行识别请求
            do {
                try VNImageRequestHandler(ciImage: ciImg).perform([request])
            } catch {
                print("执行图像识别请求失败, 原因是: \(error.localizedDescription)")
            }
            
        }
        picker.dismiss(animated: true, completion: nil)
        
    }
    
}


